-- 游戏中使用的定时器

-- 模块定义
local M = {};
setmetatable (M, {__index = _G;});
_ENV = M;

-- 状态变量
timerMap = require ("collections.MapSafeIter").NewMapSafeIter ();
timerIdGenerator = require ("tools.IdGenerator").NewIdGenerator (1, 10000000);

-- 注册定时器
-- @intervals 触发的时间间隔
-- @times 触发的次数
-- @param 回调参数，会传回func_callback
-- @func_callback 定时器回调函数，签名如 
--    callback (timer_id, current_times, param)
--      * timer_id: 定时器的ID
--      * current_times: 当前触发是第几次
--      * param: 创建定时器时传入的的param参数
-- @return timer_id 为该定时器生成的id，int类型
function AddTimer (intervals, times, param, func_callback)
    if (times < 1) then
        error ("定时器的触发次数至少是1次");
    end;
    local timer_id = timerIdGenerator:GetNextId ();
    local timer_info = 
    {
        timer_id = timer_id,
        intervals = intervals,
        times = times,
        param = param,
        func_callback = func_callback,

        tick_duration = 0,
        callback_times = 0,
        
        Update = function (info, current_time, delta_time)
            info.tick_duration = info.tick_duration + delta_time;
            if (info.tick_duration >= info.intervals) then
                info.tick_duration = 0;
                info.callback_times = info.callback_times + 1;
                if (info.callback_times >= info.times) then
                    timerMap:Rmv (info.timer_id);
                end;
                info.func_callback (info.timer_id, info.callback_times, info.param);
            end;
        end
    }
    timerMap:Add (timer_id, timer_info);  
    return timer_id;
end;

-- 停止定时器并删除
function RmvTimer (timer_id)
    timerMap:Rmv (timer_id); 
end;

-- 更新内部状态
function Update (current_time, delta_time)
    timerMap:BeginIter ();
    for _timer_id, _timer_info in timerMap:GetIter () do
        _timer_info:Update (current_time, delta_time)
    end;
    timerMap:EndIter ();
end;


return M;
